package userFileModuleApi

import (
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"fmt"
	"path/filepath"
	"strings"
	"time"
)

type UserFileModuleApi struct{}

// parseFilePath 解析文件路径，提取用户ID和文件名
func parseFilePath(filePath string) (string, string, error) {
	// 使用星号分割 filePath
	parts := strings.Split(filePath, "*")
	if len(parts) != 2 {
		return "", "", fmt.Errorf("无效的文件路径")
	}

	randomStringAndUserID := parts[0]
	fileName := parts[1]

	// 去除最后5位随机字符串，获取用户ID
	if len(randomStringAndUserID) < 5 {
		return "", "", fmt.Errorf("用户ID前的随机字符串不足5位")
	}
	userID := randomStringAndUserID[:len(randomStringAndUserID)-5]

	return userID, fileName, nil
}

// encryptFilePath 加密文件路径，将用户ID和文件名加密后返回
func encryptFilePath(userID model.SnowflakeIdType, coverImagePath string) string {
	return fmt.Sprintf("%s/%d%s*%s", "api/file/getCoverImage", userID, utils.RandomString(5), filepath.Base(coverImagePath))
}

func autoRename(filePid model.SnowflakeIdType, userId model.SnowflakeIdType, fileName string) (string, error) {
	bol, err := utils.CheckSameNameFileOrDir(filePid, userId, fileName, enums.File)
	if err != nil {
		return fileName, err
	}
	if bol {
		return utils.Rename(fileName), nil
	}
	return fileName, nil
}

func cachePreviewIdOfFileInfo(previewId string, filePath string) error {
	if previewId == "" {
		return fmt.Errorf("previewId为空")
	}
	Key := fmt.Sprintf("previewId:%s", previewId)
	if err := global.Redis.Set(Key, filePath, time.Duration(2)*time.Minute).Err(); err != nil {
		return err
	}
	return nil
}
func getPreviewIdOfFileInfo(previewId string) (string, error) {
	if previewId == "" {
		return "", fmt.Errorf("previewId为空")
	}
	Key := fmt.Sprintf("previewId:%s", previewId)
	filePath, err := global.Redis.Get(Key).Result()
	if err != nil {
		return "", err
	}
	if err = global.Redis.Expire(Key, time.Duration(2)*time.Minute).Err(); err != nil {
		return "", err
	}
	return filePath, nil
}
